<?php
class server_list {
    var $port = 0;
    var $cached_file;

    function server_list($currentServer) {
        include_once('includes/cache.php');
        include_once('includes/addMessage.php');

        global $db, $lang, $skin_dir, $properties;

        $cache = new cache('ServerList',600);
        $this->cached_file = $cache->filename;

        if($cache->valid) {

            //Check we have a valid server
            $q = 'SELECT lv_port, lv_id = ' . $currentServer . ' as current
                  FROM ' . LIVEVIEWS_TABLE . '
                  WHERE lv_enabled = 1 
                  ORDER BY current DESC, lv_class ASC, lv_id ASC
                  LIMIT 1';
            $result = $db->sql_query($q);
            if($row = $db->sql_fetchrow($result)) {
                $this->port = $row['lv_port'];
            }
        }

        else {
            include_once('includes/rfquery/rFQuery.php');
            
            $q = 'SELECT * FROM ' . LIVEVIEWS_TABLE . ' WHERE lv_enabled = 1 ORDER BY lv_class ASC, lv_id ASC';
            $curPort = 0;
            $curClass = "";
            $links = '';
            $found = false;
            $result = $db->sql_query($q);
            while($row = $db->sql_fetchrow($result)) {

                $rFq = new rFQuery($properties['rfactor_serverip'], $row['lv_port'], false);
                $rFq->SetHideServerPrefix($properties['rfactor_hideserver']);

                if($rFq->_queryServerInfo(1,false))
                {
                    if($row['lv_class'] != $curClass)
                    {
                        $links .= '<br/>' . $row['lv_class'] . '<br/>';
                        $curClass = $row['lv_class'];
                    }

                    if($row['lv_id'] == $currentServer || $curPort == 0) {
                        $curPort = $row['lv_port'];
                    }
                    $links .= '+ <a href="liveview.php?id=' . $row['lv_id'] . '">'.$row["lv_title"].'</a><br/>';
                }
            }


            $title = $lang['ServerList'];
            
            include($skin_dir . 'tpl/sidemenuhead.tpl');

            $cache->writeCache();
            $this->port = $curPort;
        }

    }

    function render() {
        include($this->cached_file);
    }
}
?>